<?php

class Admin_UsuariosController extends App_Controller_Action
{
    private $_table     = 'USUARIOS';
    private $_pk        = 'USU_ID';
    private $_order_col = 'USU_NOME';
    private $_order     = 'ASC';
    private $_sta_col   = '';
    private $obj        = '';
    private $form       = '';
    private $_file_col  = 'USU_FILE'; 
    public  $dir        = 'public/upload/';
    
    private $_PER_ID;
    private $_USU_ID;
    
    public function init()
    {
        /* Initialize action controller here */
        $auth = Zend_Auth::getInstance();
        $s_user = $auth->getStorage();
        $this->_PER_ID = $s_user->read()->PER_ID;
        $this->_USU_ID = $s_user->read()->USU_ID;
    }

    public function indexAction() {
        Zend_Loader::loadClass('tools','library');
        
        
        $where = 'TUS_ID = 1'; //USU_TPO = 1';
        if($this->_PER_ID <> 1){ // <> de administrador
            $where .= ' and USU_ID = '.$this->_USU_ID; // usuario logado
        }
        
        $USU_STA = $this->_getParam('USU_STA', 1);
        $where .= ' and USU_STA = "'.$USU_STA.'"';
        
        
        $dscfiltro = $this->_getParam('dscfiltro', '');
        
        if($dscfiltro != '') $where .= ' AND USU_NOME like "%' . $dscfiltro.'%"';
        
        $this->view->dscfiltro = $dscfiltro;
        
        
        $query = 'SELECT SQL_CACHE u.*, p.PER_NOME FROM '.$this->_table.' u, PERMISSAO p '
                . 'WHERE u.PER_ID = p.PER_ID AND '.$where.' '
                .' ORDER BY '.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result);
    }
    
    
    public function editAction() {
        $form = new Admin_Form_Usuarios();
        //$form->submit->setLabel('Gravar');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_usuarios.js?1=2');
        
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                if ($form->isValid($formData)) {
                    $id = (int) $form->getValue('USU_ID');
                    $data = array(
                        'USU_ID'        => $form->getValue('USU_ID'),
                        'USU_LOGIN'     => $form->getValue('USU_LOGIN'),	
                        //'USU_SENHA'     => sha1($form->getValue('USU_SENHA')),	
                        'USU_NOME'      => $form->getValue('USU_NOME'),
                        'USU_EMAIL'     => $form->getValue('USU_EMAIL'),
                        'PER_ID'        => $form->getValue('PER_ID'),
                        'USU_DATCAD'=> date('Y-m-d'),
                        //'USU_TPO'       => 1, // 1 = usuário
                        'TUS_ID'        => 1, 
                        'USU_CADSTA'    => 1,
                        'USU_STA'       => $form->getValue('USU_STA'),  
                    );

                    if(strlen($form->getValue('USU_SENHA')) > 1){
                        $data['USU_SENHA'] = sha1($form->getValue('USU_SENHA'));
                    }
                    $obj = new Admin_Model_DbTable_Usuarios();

                    if ($id == 0)
                        $obj->insert($data);
                    else
                        $obj->update($data, 'USU_ID = ' . $id);

                    $this->_helper->redirector('index');
                } else {
                    $form->populate($formData);
                }
            } catch(Exception $ex) {
                Zend_Loader::loadClass('errordb','library');
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                //echo $ex->getCode().'<br>';       
                //echo $ex->getMessage().'<br>';
                $form->populate($formData);
            }
        } else {
            $id = $this->_getParam('id', 0);
            
            if($this->_PER_ID <> 1){ // <> de administrador
                if($this->_USU_ID <> $id){ // <> cod usuário logado
                    $this->_helper->redirector('index');
                }
            }
            
            if ($id > 0) {
                $obj = new Admin_Model_DbTable_Usuarios();
                $form->populate($obj->fetchRow('USU_ID = ' . $id)->toArray());
            }
        }
    }

    public function deleteAction() {
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        
        $ok = FALSE;
        
        $id = $this->_getParam('id', 0);
        if ((int)$id > 0 ) {
            $obj = new Admin_Model_DbTable_Usuarios();
            //$ok = (bool) $obj->delete('USU_ID = '.(int)$id);
            $data = array('USU_STA' => 0);
            $ok = (bool) $obj->update($data, 'USU_ID = ' . $id);
        }
        
        echo json_encode(array('ok' => $ok));
    }
    
    public function validarloginAction() {
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        
        $ok = FALSE;
        $msg = '';
        
        $id = $this->_getParam('id', 0);
        $login = trim($this->_getParam('login', ''));
        
        $where = '';
        if($id > 0){
            $where = 'ALU_ID = '.$id.' ';
            $row = $this->obj->fetchRow($where);
            $where = '';
            if($row->USU_ID > 0) $where = 'USU_ID <> '.$row->USU_ID.' and ';
        }
        
        $obj = new Admin_Model_DbTable_Usuarios();
        
        $where .= 'USU_LOGIN like "'.$login.'"';
        $result = $obj->fetchAll($where);
            
        foreach($result as $res){
            if($res->USU_LOGIN == $login){
                $ok = TRUE;
                $msg = 'Login já cadastrado';
            }
        }
 
        echo json_encode(array('ok' => $ok, 'msg' => $msg));
    }

}